<template>
    <div class="api-info forbid-select">
        <el-descriptions title="接口信息" :column="5" border class="user-info">
            <el-descriptions-item label="接口Token" width="200">
                <span>{{ getUserInfo.apiToken }}</span>
                <span class="operation-content cursor-pointer">
                    <el-icon class="operation-icon" @click="copyToken">
                        <CopyDocument />
                    </el-icon>
                </span>
            </el-descriptions-item>
            <el-descriptions-item label="当前等级" width="100">{{ interfaceUsage.limit?.lv }}</el-descriptions-item>
            <el-descriptions-item label="调用次数" width="150">
                <span>{{ interfaceUsage.limit?.total + "次/天" }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="QPS" width="150">
                {{ interfaceUsage.limit?.count + "次/" + (interfaceUsage.limit?.time === 1 ? "" :
                    interfaceUsage.limit?.time) +
                    "秒" }}
            </el-descriptions-item>
            <el-descriptions-item label="今日已使用" width="150">
                {{ interfaceUsage.usage || 0 }}
            </el-descriptions-item>
        </el-descriptions>
        <div class="title">
            <span>接口调用历史记录</span>
            <div class="left history">
                <div class="button cursor-pointer" @click="showHistoryHelp">?</div>
            </div>
            <div class="right">
                <span class="pageDesc">
                    共{{ historyQuery.totalPage }}页/{{ historyQuery.totalRecords }}条 当前第{{ historyQuery.page }}页
                </span>
                <div :class="`button cursor-pointer ${historyQuery.page === 1 ? 'is-disabled' : ''}`"
                    @click="pageSizeChange('prev')" v-limitClick>
                    <el-icon>
                        <ArrowLeft />
                    </el-icon>
                </div>
                <div :class="`button cursor-pointer ${historyQuery.page === historyQuery.totalPage ? 'is-disabled' : ''}`"
                    @click="pageSizeChange('next')" v-limitClick>
                    <el-icon>
                        <ArrowRight />
                    </el-icon>
                </div>
                <div class="button cursor-pointer" @click="showHistorySearch = true">
                    <el-icon>
                        <Search />
                    </el-icon>
                </div>
                <div class="button cursor-pointer" @click="resetHistory" v-limitClick>
                    <el-icon>
                        <Refresh />
                    </el-icon>
                </div>
            </div>
        </div>
        <el-table :data="history" border header-cell-class-name="el-table-header-cell" cell-class-name="el-table-cell"
            class="e-page history-table" v-loading="historyQuery.loading">
            <template #empty>
                <div>
                    <div>暂无数据</div>
                </div>
            </template>
            <el-table-column prop="sequence" label="日志ID" width="180px" />
            <el-table-column prop="url" label="地址" min-width="300px">
                <template #default="scope">
                    <span>{{ "https://api.dansj.cn" + scope.row.url }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="params" label="参数" min-width="300px" />
            <el-table-column prop="method" label="接口方法" width="120px">
                <template #default="scope">
                    <el-tag :type="scope.row.method === 'GET' ? 'primary' : 'success'" class=" button-auto-resize">
                        {{ scope.row.method }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="start_time" label="请求时间" width="190px" />
            <el-table-column prop="end_time" label="结束时间" width="190px" />
            <el-table-column prop="cost" label="耗时" width="150px">
                <template #default="scope">
                    <span>{{ scope.row.cost + "ms" }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120px">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" class=" button-auto-resize">
                        {{ scope.row.status === 1 ? "成功" : "失败" }}
                    </el-tag>
                </template>
            </el-table-column>
        </el-table>
        <div class="title">
            <span>短链接查询</span>
            <div class="left">
                <div class="button cursor-pointer" @click="showHelp">?</div>
            </div>
            <div class="right">
                <div class="button cursor-pointer" @click="showSearch = true">
                    <el-icon>
                        <Search />
                    </el-icon>
                </div>
                <div class="button cursor-pointer" @click="resetGet" v-limitClick>
                    <el-icon>
                        <Refresh />
                    </el-icon>
                </div>
            </div>
        </div>
        <el-table :data="tableData" border header-cell-class-name="el-table-header-cell" cell-class-name="el-table-cell"
            class="shortlink-table">
            <template #empty>
                <div>
                    <div>暂无数据</div>
                    <div v-if="searchForm.shortlink || searchForm.url || searchForm.comment || searchForm.date">
                        <span>当前查询条件=></span>
                        <span v-if="searchForm.shortlink" style="padding-right: 20px;">
                            短链接：{{ searchForm.shortlink }}
                        </span>
                        <span v-if="searchForm.url" style="padding-right: 20px;">
                            长链接：{{ searchForm.url }}
                        </span>
                        <span v-if="searchForm.comment" style="padding-right: 20px;">
                            备注：{{ searchForm.comment }}
                        </span>
                        <span v-if="searchForm.date">
                            创建时间：{{ searchForm.date.join("~") }}
                        </span>
                    </div>
                </div>
            </template>
            <el-table-column prop="short_link" label="短链接" min-width="300px" />
            <el-table-column prop="url" label="长链接" min-width="400px" />
            <el-table-column prop="comment" label="备注信息" width="400px" />
            <el-table-column prop="create_time" label="创建时间" width="200px" />
            <el-table-column prop="expire_time" label="过期时间" width="200px" />
            <el-table-column fixed="right" label="操作" width="100px">
                <template #default="scope">
                    <el-button type="primary" :icon="getIcon('CopyDocument')" class="button-auto-resize" circle
                        @click="copyShortlink(scope.row.short_link)" />
                    <el-button type="danger" :icon="getIcon('delete')" class="button-auto-resize" circle
                        confirm-title="是否确认删除该接口?" @click="deleteLink(scope.row)" />
                </template>
            </el-table-column>
        </el-table>
        <el-drawer :show-close="false" size="130px" v-model="showSearch" direction="ttb"
            class="search-drawer forbid-select" append-to-body>
            <template #header>
                <h3>短链接查询条件</h3>
            </template>
            <el-form inline :model="searchForm" class="e-page form-item" spellcheck="false" @submit.native.prevent>
                <el-row>
                    <el-col :span="4">
                        <el-form-item label="短链接">
                            <el-input v-model="searchForm.shortlink" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="长链接">
                            <el-input v-model="searchForm.url" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="备注">
                            <el-input v-model="searchForm.comment" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="创建时间">
                            <el-date-picker v-model="searchForm.date" type="daterange" unlink-panels range-separator="-"
                                start-placeholder="开始时间" end-placeholder="结束时间" :shortcuts="shortcuts"
                                class="cursor-pointer" :disabled-date="disabledDate" format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD" :cell-class-name="cursorClass" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="过期时间">
                            <el-date-picker v-model="searchForm.expire" type="daterange" unlink-panels
                                range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间"
                                :shortcuts="shortcutsExpire" class="cursor-pointer" format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD" :cell-class-name="cursorClass" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="1">
                        <el-button type="primary" @click="search" circle :icon="Search" v-limitClick
                            :disabled="!(searchForm.shortlink || searchForm.url || searchForm.comment || searchForm.date.length || searchForm.expire.length)" />
                    </el-col>
                </el-row>
            </el-form>
        </el-drawer>
        <el-drawer :show-close="false" size="130px" v-model="showHistorySearch" direction="ttb"
            class="search-drawer forbid-select" append-to-body>
            <template #header>
                <h3>接口历史记录查询条件</h3>
            </template>
            <el-form inline :model="historySearchForm" class="e-page form-item" spellcheck="false"
                @submit.native.prevent>
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="地址">
                            <el-input v-model="historySearchForm.url" placeholder="不包含https://api.dansj.cn部分" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="参数">
                            <el-input v-model="historySearchForm.param" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="接口方法">
                            <el-select v-model="historySearchForm.method" class="input-auto-resize" clearable
                                cell-class-name="normal-poper cursor-pointer" placeholder="请选择接口方法">
                                <el-option :label="item" :value="item" v-for="(item, index) in ['GET', 'POST']"
                                    :key="index" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="状态">
                            <el-select v-model="historySearchForm.status" class="input-auto-resize" clearable
                                cell-class-name="normal-poper cursor-pointer" placeholder="请选择接口状态">
                                <el-option :label="item.text" :value="item.status"
                                    v-for="(item, index) in [{ status: 1, text: '成功' }, { status: 0, text: '失败' }]"
                                    :key="index" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="请求时间">
                            <el-date-picker v-model="historySearchForm.date" type="daterange" unlink-panels
                                range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间"
                                :shortcuts="shortcuts" class="cursor-pointer" :disabled-date="disabledDate"
                                format="YYYY-MM-DD" value-format="YYYY-MM-DD" :cell-class-name="cursorClass" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="1">
                        <el-button type="primary" @click="getInterfaceRecord" circle :icon="Search" v-limitClick
                            :disabled="!(historySearchForm.url || historySearchForm.param || historySearchForm.method || historySearchForm.status === 1 || historySearchForm.status === 0 || historySearchForm.date.length)" />
                    </el-col>
                </el-row>
            </el-form>
        </el-drawer>
    </div>
</template>

<script setup>
import { storeToRefs, useUserStore } from "@/pinia"
import { useRequest, useCopyText, useElMessageBox, useElMessage } from "@/hooks"
import { CopyDocument, Refresh, Search, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { getIcon } from "@/utils/tools"

const userStore = useUserStore()
const { getUserInfo } = storeToRefs(userStore)
let showSearch = $ref(false)
let showHistorySearch = $ref(false)
let searchForm = $ref({ shortlink: "", url: "", date: [], comment: "", expire: [] })
let historySearchForm = $ref({ url: "", param: "", method: "", status: "", date: [] })
let interfaceUsage = $ref({ limit: { total: 0, count: 0, time: 1 } })
let history = $ref([])
let historyQuery = $ref({ page: 1, limit: 10, totalPage: 0, totalRecords: 0, loading: false })

const shortcuts = [
    {
        text: '近一周',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        },
    },
    {
        text: '近一个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 1)
            return [start, end]
        },
    },
    {
        text: '近三个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 3)
            return [start, end]
        },
    },
]

const cursorClass = () => "cursor-pointer"

const shortcutsExpire = [
    {
        text: '近一周',
        value: () => {
            const end = new Date()
            const start = new Date()
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 7)
            return [start, end]
        },
    },
    {
        text: '近一个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            end.setMonth(end.getMonth() + 1)
            return [start, end]
        },
    },
    {
        text: '近三个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            end.setMonth(end.getMonth() + 3)
            return [start, end]
        },
    },
]

const disabledDate = (date) => {
    return date.getTime() > Date.now()
}

const search = () => {
    getlink({ ...searchForm, date: searchForm.date?.join("|"), expire: searchForm.expire?.join("|") })
}

const copyToken = () => {
    useCopyText(getUserInfo.value.apiToken).then(() => useElMessage.success("token复制成功"))
}

let tableData = $ref([])

const resetGet = () => {
    searchForm = { shortlink: "", url: "", date: [], comment: "", expire: [] }
    getlink()
}
const getlink = (data = {}) => {
    useRequest("https://api.dansj.cn/getLink", { ...data }).then(resp => {
        if (resp && resp.status) {
            tableData = resp.data
        }
    })
}

const getInterfaceRecord = () => {
    if (historyQuery.loading) return
    historyQuery.loading = true
    useRequest.get("https://api.dansj.cn/interfaceRecord", { page: historyQuery.page, limit: historyQuery.limit, ...historySearchForm, date: historySearchForm.date ? historySearchForm.date.join("|") : "" }).then(resp => {
        if (resp && resp.status) {
            history = resp.data
            if (historyQuery.totalPage !== resp.totalPage) historyQuery.totalPage = resp.totalPage
            if (historyQuery.totalRecords !== resp.totalRecords) historyQuery.totalRecords = resp.totalRecords
        }
    }).finally(() => historyQuery.loading = false)
}

const getInterfaceTodayUse = () => {
    useRequest("https://api.dansj.cn/interfaceUsage").then(resp => {
        if (resp && resp.status) {
            interfaceUsage.limit = resp.data.limit
            interfaceUsage.usage = resp.data.todayCount
        }
    })
}

const copyShortlink = (v) => {
    useCopyText(v).then(() => useElMessage.success("短链接地址复制成功"))
}

const deleteLink = (row) => {
    useElMessageBox("删除提示", "确认删除该短链接? 删除后将无法恢复, 请确认是否继续", { type: "warning", showCancelButton: true }).then(() => {
        useRequest.post({ url: "https://api.dansj.cn/removeShortLink", shortlink: row.slink }).then(resp => {
            if (resp && resp.status) {
                getlink()
                useElMessage.success("短链接删除成功")
            } else {
                useElMessage.error(resp.message)
            }
        }).catch((resp) => {
            useElMessage.error("删除短链接失败")
        })
    })
}

const showHelp = () => {
    useElMessageBox("短链接说明", h('p', null, [
        h('div', null, '1. 短链接在跳转长链接时，使用的301重定向'),
        h('div', null, '2. 长链接如果未填写http或者https前缀时，默认跳转https'),
        h('div', null, '3. 短链接默认30天有效期，过期后将失效，如需永久有效，请联系管理员'),
        h('div', null, '4. 最多同时创建50个短链接，超出后请删除其他短链接以继续创建新的短链接')
    ]), { showIcon: false, customClass: "", showClose: true, showConfirmButton: false, closeOnClickModal: true })
}

const showHistoryHelp = () => {
    useElMessageBox("接口历史记录查询说明", h('p', null, [
        h('div', null, '1. 能够查询通过token调用的接口记录，通过系统内部Token调用的测试记录不在查询范围内'),
        h('div', null, '2. 查询有一分钟缓存，如果没有最新数据请稍后查询'),
        h('div', null, '3. 如果缺失记录数据，请联系管理员查询')
    ]), { showIcon: false, customClass: "", showClose: true, showConfirmButton: false, closeOnClickModal: true })
}

const pageSizeChange = (t) => {
    if (historyQuery.loading) return
    if (t === 'next' && historyQuery.page < historyQuery.totalPage) {
        historyQuery.page++
    } else if (t === 'prev' && historyQuery.page > 1) {
        historyQuery.page--
    } else {
        console.log(111)
        return
    }

    getInterfaceRecord()
}

const resetHistory = () => {
    if (historyQuery.loading) return
    historyQuery.page = 1
    historySearchForm = { url: "", param: "", method: "", status: "", date: [] }
    getInterfaceRecord()
}

getlink()
getInterfaceRecord()
getInterfaceTodayUse()
</script>

<style>
.api-info {
    height: 100%;
}

.api-info .token {
    height: 30px;
    line-height: 30px;
    font-size: 18px;
    padding: 5px 0;
}

.api-info .token span:first-child {
    width: 10%;
    min-width: 120px;
    display: inline-block;
    text-align: right;
    padding-right: 20px;
}

.c-token {
    height: 100%;
    display: inline-block;
    aspect-ratio: 1;
}

.copy-token {
    top: calc((100% - 1em));
    transform: translateY(-50%);
    left: calc((100% - 1em));
    color: blueviolet;
    cursor: pointer;
}

/*多一个分页高度50px*/
.api-info .shortlink-table {
    height: calc(50% - 97px);
    /* background: rgba(255, 255, 255, .7); */
    background: transparent;
}

/*多一个分页高度50px*/
.api-info .history-table {
    height: calc(50% - 95px);
    /* background: rgba(255, 255, 255, .7); */
    background: transparent;
}

.api-info .title {
    font-size: 18px;
    margin: 16px 0;
    font-weight: bold;
    color: var(--el-text-color-primary);
    position: relative;
}

.api-info .title .left {
    position: absolute;
    left: 100px;
    top: 50%;
    transform: translateY(-50%);
    display: flex;
}

.api-info .title .history {
    left: 160px;
}

.api-info .title .right {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    display: flex;
}

.search-drawer .el-form--inline .el-form-item {
    margin-bottom: 0;
    margin-right: 0;
    width: 95%;
}

.search-drawer .el-drawer__header {
    margin: 0 !important;
}

.search-drawer .el-drawer__header h3 {
    margin: 0 !important;
}

.search-drawer .el-form-item__label {
    font-size: 16px;
}

.search-drawer .el-date-editor .el-range-input {
    font-family: inherit;
}

.api-info .el-table__empty-block {
    display: block;
}

.api-info .pageDesc {
    display: flex;
    align-items: center;
    font-weight: normal;
    padding-right: 10px;
    font-size: 16px;
}
</style>
